package com.yaolaizaixian.merchant.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.victor.loading.rotate.RotateLoading;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.adapter.FragmentSalesWeekAdapter;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.SalesWeekData;
import com.yaolaizaixian.merchant.bean.SalesWeekList;
import com.yaolaizaixian.merchant.bean.SalesWeekModel;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by ylzx on 2017/2/27.
 * 本月销售列表
 */
public class Fragment_SalesMonth extends Fragment {

    private static final String TAG = "Fragment_SalesMonth";
    @BindView(R.id.xrv_orderlist)
    XRecyclerView xrvOrderlist;
    @BindView(R.id.iv_kong)
    ImageView ivKong;
    @BindView(R.id.rl_kong)
    RelativeLayout rlKong;
    @BindView(R.id.rotateloading)
    RotateLoading rotateloading;


    //用户
    private String userId;
    //页数
    private int pageNum = 1;

    private FragmentSalesWeekAdapter fragmentSalesWeekAdapter;
    private List<SalesWeekList> totalSales;

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {

                        final SalesWeekModel salesWeekModel = GsonUtil.jsonToBean(result, SalesWeekModel.class);

                        SalesWeekData data = salesWeekModel.getData();
                        List<SalesWeekList> salesWeekDatas = data.getList();
                        if (null != salesWeekDatas && salesWeekDatas.size() > 0) {

                            if (pageNum == 1) {

                                totalSales.clear();
                                totalSales.addAll(salesWeekDatas);

                            } else {
                                totalSales.addAll(salesWeekDatas);
                            }


                        }


                        if (totalSales.size() <= 0) {

                            rlKong.setVisibility(View.VISIBLE);
                        }

                        if (null == fragmentSalesWeekAdapter) {

                            fragmentSalesWeekAdapter = new FragmentSalesWeekAdapter(getActivity(), totalSales, data.getStroeName());

                            xrvOrderlist.setAdapter(fragmentSalesWeekAdapter);

                        } else {

                            fragmentSalesWeekAdapter.notifyDataSetChanged();

                        }
                        if (pageNum == 1) {

                            xrvOrderlist.refreshComplete();

                        } else {
                            xrvOrderlist.loadMoreComplete();
                        }

                            dissmiss();
                    } else {

                            dissmiss();
                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            SalesRecordActivity activity = (SalesRecordActivity) getActivity();
//                            activity.showConflictDialog("账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            SalesRecordActivity activity = (SalesRecordActivity) getActivity();
//                            activity.showConflictDialog("您的账号在其它设备登录");

                        } else {
                            rlKong.setVisibility(View.VISIBLE);
                            Toast.makeText(getActivity(), baseModel.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;
                        }

                    }
                    break;


            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_salesmonth, container, false);

        ButterKnife.bind(this, view);
        totalSales = new ArrayList<>();

        initData(view);

        return view;
    }

    private void initData(View view) {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xrvOrderlist.setLayoutManager(layoutManager);
        xrvOrderlist.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrvOrderlist.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        xrvOrderlist.setArrowImageView(R.mipmap.iconfont_downgrey);

        //用户id
        userId = SharedPreferencesUtil.getString(getActivity(), "usersysno", "");

        //上拉刷新
        xrvOrderlist.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum = 1;

                        getData(pageNum + "");

                    }

                }, 1000);

            }

            //加载更多
            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum += 1;
                        getData(pageNum + "");

                    }
                }, 1000);


            }
        });

        showloading(view);
        //获取数据
        getData(pageNum + "");


    }


    /**
     * 本月销售
     */
    private void getData(String pageNum) {

        try {
            final String url = BaseInfo.URL + "lifeOrder/getMyLifeSalesList.do";
            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            sortedParams.put("userId", userId);
            sortedParams.put("pageSize", "10");
            sortedParams.put("pageNum", pageNum);
            sortedParams.put("type", "month");
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getActivity().getApplicationContext()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            dissmiss();
            rlKong.setVisibility(View.VISIBLE);
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {
            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

    private void dissmiss() {

        if (rotateloading.isStart()) {

            rotateloading.stop();
        }

    }

    private void showloading(View view) {

        rotateloading = (RotateLoading) view.findViewById(R.id.rotateloading);

        rotateloading.start();
    }

}
